package com.youxuit.youxu.kecheng.threadLocal.usage2;

import java.util.concurrent.ConcurrentHashMap;

/*
分数统计
 */
public class NotSafeHashMap implements Runnable {

    public static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    static String name = "小咪咕";

    public static void main(String[] args) throws InterruptedException {
        map.put(name, 0);

        Thread thread1 = new Thread(new NotSafeHashMap());
        Thread thread2 = new Thread(new NotSafeHashMap());

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(map);


    }

    @Override
    public void run() {


        for (int i = 0; i < 1000; i++) {
            //Integer currentScores = map.get(name);
            //int newScores = currentScores + 1;
            //map.put(name, newScores);


            //
            /*//synchronized (this) {
            //    int currentScores = map.get(name);
            //    int newScores = currentScores + 1;
            //    map.put(name, newScores);
            //}*/
            while (true) {

                Integer currentScores = map.get(name);
                int newScores = currentScores + 1;
                boolean replace = map.replace(name, currentScores, newScores);
                if (replace) {
                    break;
                }
            }
        }


    }
}
